package handler

import (
	"context"
	"fmt"
	baseStore "gitee.com/zaiqiang231/go-base-app/base_app/store"
	"gitee.com/zaiqiang231/zcamp-service-camp/app/model"
	"gitee.com/zaiqiang231/zcamp-service-camp/app/rpc/proto"
	"gorm.io/gorm"
	"sync"
)

var (
	postSever     *PostServer
	oncePostSever sync.Once
)

type PostServer struct {
}

func GetPostServer() (*PostServer, error) {
	oncePostSever.Do(func() {
		postSever = &PostServer{}
	})

	if postSever == nil {
		return nil, fmt.Errorf("got nil server")
	}

	return postSever, nil
}

func (s *PostServer) GetUserPostInfo(ctx context.Context, r *proto.UserPostInfoRequest) (*proto.UserPostInfoResponse, error) {
	var err error
	var postCount = make(map[int64]int)
	baseStore.GetDataStore().Execute(func(db *gorm.DB) {
		err = db.Transaction(func(tx *gorm.DB) error {
			for _, uid := range r.Ids {
				var count int64
				txErr := tx.Model(&model.PostInfo{}).Where("uid = ?", uid).Count(&count).Error
				if txErr != nil {
					postCount[uid] = 0
				} else {
					postCount[uid] = int(count)
				}
			}
			return nil
		})
	})
	if err != nil {
		return nil, err
	}
	response := proto.UserPostInfoResponse{}
	list := make([]*proto.UserPostInfoItem, 0)
	for _, uid := range r.Ids {
		list = append(list, &proto.UserPostInfoItem{
			Uid:     uid,
			PostNum: int64(postCount[uid]),
		})
	}
	response.List = list
	return &response, nil
}
